import { BaseContext } from "koa";
import { getRepository } from "typeorm";
import authorize from "../../middleware/authorize";
import { Get, Post, Controller } from "../../middleware/request";
import { Exception } from "../../utils/exception";
// import { User } from "../entity/User";
import { auth as Auth } from "../../utils/auth";
import { encrypt, decrypt } from "../../utils/crypto";
const fs = require('fs')
const path = require('path')
@Controller("/api")
export class uploadFileController {
  @Post("/uploadFile")
  async uploadFile(ctx: BaseContext) {
    try {
      const file = ctx.request.files.file;
      // 创建可读流
      const render = fs.createReadStream(file.path);
      let filePath = path.join(__dirname, '../../public/imgs', file.name);
      let filePath1 = path.join(__dirname, '../../../../store-server-master/public/imgs', file.name);
      const fileDir = path.join(__dirname, '../../public/imgs');
      const fileDir1 = path.join(__dirname, '../../../../store-server-master/public/imgs');
      if (!fs.existsSync(fileDir)) {
        fs.mkdirSync(fileDir, (err: any) => {
          console.log(err)
          console.log('创建失败')
        });
      }
      if (!fs.existsSync(fileDir1)) {
        fs.mkdirSync(fileDir1, (err: any) => {
          console.log(err)
          console.log('创建失败')
        });
      }
      // 创建写入流
      const upStream = fs.createWriteStream(filePath);
      render.pipe(upStream);
      const upStream1 = fs.createWriteStream(filePath1);
      render.pipe(upStream1);
      ctx.body = {
        ...Exception(200, '上传成功'),
        data: {
          url: 'public/imgs/' + file.name
        }
      }
    } catch (error) {
      ctx.body = Exception(112, "上传失败");
    }
  }

}
